﻿using EFAPIProject.Entities;
using static EFAPIProject.Repositories.IRepository;

namespace EFAPIProject.Services
{
    public class UserService
    {
        private readonly IRepository<User> _userRepository;

        // 注入用户仓储
        public UserService(IRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        // 新增用户
        public async Task<int> CreateUserAsync(string userName, string email, int? age = null)
        {
            // 验证邮箱是否已存在
            if (await _userRepository.ExistsAsync(u => u.Email == email))
                throw new ArgumentException("邮箱已被注册");

            var user = new User
            {
                UserName = userName,
                Email = email,
                Age = age
                // CreateTime 由数据库默认值生成，无需手动赋值
            };

            await _userRepository.AddAsync(user);
            await _userRepository.SaveChangesAsync();
            return user.Id; // 返回新增用户的ID
        }

        // 条件查询（例如：查询成年用户）
        public async Task<List<User>> GetAdultUsersAsync()
        {
            return await _userRepository.GetFilteredAsync(u => u.Age != null && u.Age >= 18);
        }
      
    }
}
